<template>

    <div class="container">

        <div class="Search">
            <el-form
                    ref="form"
                    label-width="auto"
                    :label-position="'left'"
                    :size="'large'"
                    inline
            >
                <el-form-item label="选择学期">
                    <el-radio-group v-model="radio" @change="changeSelect">
                        <el-radio v-for="item in semester.values()" :label="item" :key="item">{{ item }}</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item>

                    <el-popover
                            placement="top-start"
                            title="导入日历"
                            :width="200"
                            trigger="hover"
                            content="ICS文件是日历软件的一种文件格式，可以在日历软件中导入"
                    >
                        <template #reference>
                            <el-button type="primary" @click="onSubmit">导入日历</el-button>
                        </template>
                    </el-popover>

                    <el-popover
                            placement="top-start"
                            title="订阅链接"
                            :width="200"
                            trigger="hover"
                            content="订阅链接可以在日历软件中添加，实现将来所有课程的自动更新"
                    >
                        <template #reference>
                            <el-button type="primary" id="copyButton" @click="copyLink">订阅链接</el-button>
                        </template>
                    </el-popover>

                    <el-button type="primary" id="copyButton" @click="toDoc">使用教程</el-button>


                    <!--                    <el-button type="primary" id="copyButton">订阅链接</el-button>-->
                </el-form-item>
            </el-form>
        </div>

        <div>
            <div class="Crouse">
                <!-- 显示Crouse中的数据-->
                <el-main>
                    <el-scrollbar>
                        <el-table v-loading="loading" :data="currentPageCrouse" class="table">
                            <el-table-column width="300px" prop="CrouseName" label="课程名称"/>
                            <el-table-column width="200px" prop="classroom" label="上课地点"/>
                            <el-table-column width="200px" prop="teacher" label="授课教师"/>
                            <el-table-column width="100px" prop="day" label="星期"/>
                            <el-table-column width="300px" prop="time[0]" label="上课周"/>
                            <el-table-column width="100px" prop="time[1]" label="上课时间"/>
                        </el-table>
                    </el-scrollbar>
                </el-main>
            </div>
            <el-pagination
                    large
                    background
                    layout="prev, pager, next"
                    :total="Crouse.length"
                    class="Plan"
                    @current-change="hanndlePageChange"
            />
        </div>
    </div>
</template>

<script lang="ts" setup>
import {ref, onMounted} from 'vue'
import axios from 'axios'
// import {CommonServerOptions} from 'vite'

const size = ref('default')
const labelPosition = ref('right')
import Clipboard from 'clipboard';
import {ElMessage} from "element-plus";


const semester = ref([]);
const radio = ref()
let Crouse = ref([])
let currentPageCrouse = ref([])
const AllCrouse = ref([])
const pageNumber = ref(10)
const loading = ref(true)
// 使用onMounted方法
onMounted(() => {
    if (localStorage.getItem('crouseRes') === null) {
        ElMessage({
            message: '登录成功',
            type: 'success',
        })
        const clipboard = new Clipboard('#copyButton', {
            text: () => {
                return 'http://' + window.location.hostname + ':7292/getCrouse?id=' + getID(); // 这里可以是你要复制的链接
            }
        });
        // 循环请求，直到获取到数据
        let timer = setInterval(() => {
            axios.get('api/getCrouse', {}).then((res: any) => {
                if (res.data.status === 'success') {
                    console.log(res.data)
                    if (res.data.key.length === 0) {
                        return
                    }
                    localStorage.setItem('crouseRes', JSON.stringify(res));
                    semester.value = res.data.key
                    radio.value = semester.value[semester.value.length - 1]
                    console.log(radio.value)
                    Crouse.value = res.data.data[res.data.key[res.data.key.length - 1]][0]
                    currentPageCrouse.value = Crouse.value.slice(0, pageNumber.value)
                    AllCrouse.value = res.data.data
                    loading.value = false
                    clearInterval(timer)
                }
            })
        }, 1000)
    } else {
        const clipboard = new Clipboard('#copyButton', {
            text: () => {
                return 'http://' + window.location.hostname + ':7292/getCrouse?id=' + getID(); // 这里可以是你要复制的链接
            }
        });
        let res = JSON.parse(localStorage.getItem('crouseRes') as string)
        semester.value = res.data.key
        radio.value = semester.value[semester.value.length - 1]
        Crouse.value = res.data.data[res.data.key[res.data.key.length - 1]][0]
        currentPageCrouse.value = Crouse.value.slice(0, pageNumber.value)
        AllCrouse.value = res.data.data
        loading.value = false
    }

})


function changeSelect(event: any) {
    Crouse.value = AllCrouse.value[event][0]
    currentPageCrouse.value = Crouse.value.slice(0, pageNumber.value)
}

function copyLink() {
    ElMessage({
        message: '链接复制成功，快去导入吧~',
        type: 'success',
    })
}

function toDoc() {
    // 跳转到新的网站
    // window.location.href = 'https://magic-H.top/6666.html'

    // 使用浏览器新建一个标签
    window.open('https://magic-H.top/6666.html')

}


// create方法

function onSubmit() {
    // 使用post方法
    axios.post('api/getCrouse', {
        data: Crouse.value,
        date: AllCrouse.value[radio.value][1]
    }).then(function (response) {
        // console.log(response.data)
        const blob = new Blob([response.data.data], {
            type: "text/calendar;charset=utf-8",
        });
        const aEle = document.createElement("a"); // 创建a标签
        const href = window.URL.createObjectURL(blob); // 创建下载的链接
        aEle.href = href;
        aEle.download = radio.value + "课程表.ics";
        document.body.appendChild(aEle);
        aEle.click();
        document.body.removeChild(aEle);
        window.URL.revokeObjectURL(href);
        ElMessage({
            message: 'ICS文件已下载，快去导入吧~',
            type: 'success',
        })
    }).catch(function (error) {
        console.log(error)
    })
}

function hanndlePageChange(val: number) {
    console.log(val)
    currentPageCrouse.value = Crouse.value.slice((val - 1) * pageNumber.value, val * pageNumber.value)
}

function getID() {
    const cookies = document.cookie.split(';'); // 将所有 Cookie 拆分成数组
    for (let i = 0; i < cookies.length; i++) {
        const cookie = cookies[i].trim().split('=');
        if (cookie[0] == 'id') {
            return cookie[1]
        }
    }
}


</script>

<style>
.el-radio-group {
    margin-right: 12px;
}

.container {
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    height: 100%;
}

.Search {
    display: flex;
    justify-content: center;
    align-items: center;
    margin: 0 auto;
    margin-top: 100px;
    margin-bottom: 20px;
}

.Crouse {
    display: flex;
    height: auto;
    width: auto;
}


</style>
